using TerritoryGame.Application.Interfaces;
using TerritoryGame.Application.Dtos;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Interfaces;
using TerritoryGame.Domain.Entities.App;
using TerritoryGame.Domain.DomainEvents;
using TerritoryGame.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using System.Text;

namespace TerritoryGame.Application.Services;

/// <summary>
/// 用户服务实现
/// </summary>
public class AppUserService : IAppUserService
{
    private readonly TerritoryGameDbContext _db;
    private readonly IDomainEventPublisher _eventPublisher;

    public AppUserService(
        TerritoryGameDbContext db,
        IDomainEventPublisher eventPublisher)
    {
        _db = db;
        _eventPublisher = eventPublisher;
    }

    /// <summary>
    /// 获取用户列表（分页）
    /// </summary>
    public async Task<ApiResult> GetUsersAsync(int page, int size, string? search = null)
    {
        try
        {
            // 参数验证
            page = Math.Max(1, page);
            size = Math.Max(1, Math.Min(size, 100)); // 限制最大页大小为100

            // 构建基础查询
            var query = _db.Users
                .Where(u => !u.IsDeleted) // 只查询未删除的用户
                .AsQueryable();

            // 应用搜索条件
            if (!string.IsNullOrEmpty(search))
            {
                query = query.Where(u => 
                    u.Username.Contains(search) || 
                    u.Email.Contains(search) || 
                    (u.Phone != null && u.Phone.Contains(search)));
            }

            // 计算总数
            var total = await query.CountAsync();

            // 分页查询 - 使用稳定的排序方式，避免启用禁用后上下跳动
            var users = await query
                .OrderBy(u => u.Username).ThenBy(u => u.Id) // 按用户名排序，然后按ID排序
                .Skip((page - 1) * size)
                .Take(size)
                .ToListAsync();

            // 转换为DTO
            var userDtos = users.Select(u => new UserListDto
            {
                Id = u.Id,
                UserName = u.Username,
                Email = u.Email,
                PhoneNumber = u.Phone,
                Avatar = u.Avatar,
                AccountStatus = u.AccountStatus,
                LastLoginTime = u.LastLoginTime,
                CreatedAt = u.CreatedAt,
                UpdatedAt = u.UpdatedAt
            }).ToList();

            // 创建分页结果
            var totalPages = (int)Math.Ceiling((double)total / size);
            var result = new
            {
                Users = userDtos,
                Total = total,
                Page = page,
                Size = size,
                TotalPages = totalPages,
                HasPreviousPage = page > 1,
                HasNextPage = page < totalPages
            };

            return ApiResult.Success("获取用户列表成功", result);
        }
        catch (Exception ex)
        {
            // 记录详细错误信息
            Console.WriteLine($"获取用户列表时发生错误: {ex.Message}");
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取用户列表时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 根据ID获取用户详情
    /// </summary>
    public async Task<ApiResult> GetUserByIdAsync(Guid userId)
    {
        try
        {
            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");

            var userDto = new UserListDto
            {
                Id = user.Id,
                UserName = user.Username,
                Email = user.Email,
                PhoneNumber = user.Phone,
                Avatar = user.Avatar,
                AccountStatus = user.AccountStatus,
                LastLoginTime = user.LastLoginTime,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt
            };

            return ApiResult.Success("获取用户详情成功", userDto);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户详情时发生错误: {ex.Message}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取用户详情时发生错误: {ex.Message}");
        }
    }



    /// <summary>
    /// 创建用户
    /// </summary>
    public async Task<ApiResult> CreateUserAsync(CreateUserDto dto)
    {
        try
        {
            // 测试数据库连接
            try
            {
                var connectionTest = await _db.Users.CountAsync();
                Console.WriteLine($"数据库连接正常，当前用户总数: {connectionTest}");
            }
            catch (Exception connEx)
            {
                Console.WriteLine($"数据库连接测试失败: {connEx.Message}");
                return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, "数据库连接失败，请稍后重试");
            }
            // 验证用户名格式
            if (string.IsNullOrEmpty(dto.UserName))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户名不能为空");
            }

            if (dto.UserName.Length < 3 || dto.UserName.Length > 50)
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户名长度必须在3-50个字符之间");
            }

            // 验证密码格式
            if (string.IsNullOrEmpty(dto.Password))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "密码不能为空");
            }

            if (dto.Password.Length < 6)
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "密码长度不能少于6个字符");
            }

            // 验证邮箱格式
            if (string.IsNullOrEmpty(dto.Email))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱不能为空");
            }

            var emailRegex = new System.Text.RegularExpressions.Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
            if (!emailRegex.IsMatch(dto.Email))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱格式不正确");
            }

            if (dto.Email.Length > 100)
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱长度不能超过100个字符");
            }

            // 验证手机号格式
            if (string.IsNullOrEmpty(dto.PhoneNumber))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号不能为空");
            }

            var phoneRegex = new System.Text.RegularExpressions.Regex(@"^1[3-9]\d{9}$");
            if (!phoneRegex.IsMatch(dto.PhoneNumber))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号格式不正确，请输入11位中国大陆手机号");
            }

            if (dto.PhoneNumber.Length != 11)
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号长度必须为11位");
            }

            // 验证用户名是否已存在
            var existingUser = await _db.Users
                .Where(u => !u.IsDeleted && u.Username == dto.UserName)
                .FirstOrDefaultAsync();

            if (existingUser != null)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户名已存在");

            // 验证邮箱是否已存在
            var existingEmail = await _db.Users
                .Where(u => !u.IsDeleted && u.Email == dto.Email)
                .FirstOrDefaultAsync();

            if (existingEmail != null)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱已存在");

            // 验证手机号是否已存在（如果提供）
            if (!string.IsNullOrEmpty(dto.PhoneNumber))
            {
                var existingPhone = await _db.Users
                    .Where(u => !u.IsDeleted && u.Phone == dto.PhoneNumber)
                    .FirstOrDefaultAsync();

                if (existingPhone != null)
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号已存在");
            }

            // 生成盐值和密码哈希
            var salt = GenerateRandomSalt();
            var hashedPassword = HashPassword(dto.Password, salt);

            // 创建用户
            var user = new User
            {
                Username = dto.UserName,
                Password = hashedPassword,
                Salt = salt,
                Email = dto.Email,
                Phone = dto.PhoneNumber, // 必填字段
                Avatar = "default-avatar.png", // 只保存文件名，不拼接路径
                AccountStatus = 0, // 正常状态
                FailedLoginAttempts = 0,
                LockedUntil = null,
                LastFailedLogin = null,
                LastActivityTime = null,
                LastLoginTime = null,
                IsActive = true,
                IsDeleted = false,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            // 保存用户
            try
            {
                Console.WriteLine($"准备保存用户: {user.Username}, ID: {user.Id}");
                Console.WriteLine($"用户数据: Email={user.Email}, Phone={user.Phone}, Avatar={user.Avatar}");
                Console.WriteLine($"用户状态: AccountStatus={user.AccountStatus}, IsActive={user.IsActive}, IsDeleted={user.IsDeleted}");
                
                _db.Users.Add(user);
                await _db.SaveChangesAsync();
                Console.WriteLine($"用户保存成功: {user.Username}");
            }
            catch (Exception saveEx)
            {
                Console.WriteLine($"保存用户时发生错误: {saveEx.Message}");
                Console.WriteLine($"错误详情: {saveEx}");
                if (saveEx.InnerException != null)
                {
                    Console.WriteLine($"内部错误: {saveEx.InnerException.Message}");
                    Console.WriteLine($"内部错误详情: {saveEx.InnerException}");
                }
                throw; // 重新抛出异常
            }

            // 发布用户创建事件
            var userCreatedEvent = new UserCreatedEvent(user, "admin", "web");
            await _eventPublisher.PublishAsync(userCreatedEvent);

            var result = new UserListDto
            {
                Id = user.Id,
                UserName = user.Username,
                Email = user.Email,
                PhoneNumber = user.Phone,
                Avatar = user.Avatar,
                AccountStatus = user.AccountStatus,
                LastLoginTime = user.LastLoginTime,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt
            };

            return ApiResult.Success("创建用户成功", result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"创建用户时发生错误: {ex.Message}");
            Console.WriteLine($"错误详情: {ex}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部错误: {ex.InnerException.Message}");
                Console.WriteLine($"内部错误详情: {ex.InnerException}");
            }
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"创建用户时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    public async Task<ApiResult> UpdateUserAsync(Guid userId, UpdateUserDto dto)
    {
        try
        {
            Console.WriteLine($"开始更新用户 - UserId: {userId}");
            Console.WriteLine($"更新数据: UserName={dto.UserName}, Email={dto.Email}, PhoneNumber={dto.PhoneNumber}");

            // 测试数据库连接
            try
            {
                var connectionTest = await _db.Users.CountAsync();
                Console.WriteLine($"数据库连接正常，当前用户总数: {connectionTest}");
            }
            catch (Exception connEx)
            {
                Console.WriteLine($"数据库连接测试失败: {connEx.Message}");
                return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, "数据库连接失败，请稍后重试");
            }

            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");

            Console.WriteLine($"找到用户: {user.Username}, 当前数据: Username={user.Username}, Email={user.Email}, Phone={user.Phone}");

            // 验证用户名
            if (!string.IsNullOrEmpty(dto.UserName))
            {
                // 检查用户名格式
                if (dto.UserName.Length < 3 || dto.UserName.Length > 50)
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户名长度必须在3-50个字符之间");
                }

                // 检查用户名是否只包含字母、数字和下划线
                if (!System.Text.RegularExpressions.Regex.IsMatch(dto.UserName, @"^[a-zA-Z0-9_]+$"))
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户名只能包含字母、数字和下划线");
                }

                // 检查用户名唯一性（只有当新值与当前值不同时才检查）
                if (dto.UserName != user.Username)
                {
                    Console.WriteLine($"检查用户名唯一性: {dto.UserName}");
                    var existingUsername = await _db.Users
                        .Where(u => !u.IsDeleted && u.Username == dto.UserName && u.Id != userId)
                        .FirstOrDefaultAsync();

                    if (existingUsername != null)
                    {
                        Console.WriteLine($"用户名已存在: {dto.UserName}");
                        return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户名已存在");
                    }
                }
                else
                {
                    Console.WriteLine($"用户名未变化: {dto.UserName}");
                }
            }

            // 验证邮箱
            if (!string.IsNullOrEmpty(dto.Email))
            {
                // 检查邮箱格式
                var emailRegex = new System.Text.RegularExpressions.Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
                if (!emailRegex.IsMatch(dto.Email))
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱格式不正确");
                }

                // 检查邮箱长度
                if (dto.Email.Length > 100)
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱长度不能超过100个字符");
                }

                // 检查邮箱唯一性（只有当新值与当前值不同时才检查）
                if (dto.Email != user.Email)
                {
                    Console.WriteLine($"检查邮箱唯一性: {dto.Email}");
                    var existingEmail = await _db.Users
                        .Where(u => !u.IsDeleted && u.Email == dto.Email && u.Id != userId)
                        .FirstOrDefaultAsync();

                    if (existingEmail != null)
                    {
                        Console.WriteLine($"邮箱已存在: {dto.Email}");
                        return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "邮箱已存在");
                    }
                }
                else
                {
                    Console.WriteLine($"邮箱未变化: {dto.Email}");
                }
            }

            // 验证手机号
            if (!string.IsNullOrEmpty(dto.PhoneNumber))
            {
                // 检查手机号格式（中国大陆手机号）
                var phoneRegex = new System.Text.RegularExpressions.Regex(@"^1[3-9]\d{9}$");
                if (!phoneRegex.IsMatch(dto.PhoneNumber))
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号格式不正确，请输入11位中国大陆手机号");
                }

                // 检查手机号长度
                if (dto.PhoneNumber.Length != 11)
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号长度必须为11位");
                }

                // 检查手机号唯一性（只有当新值与当前值不同时才检查）
                if (dto.PhoneNumber != user.Phone)
                {
                    Console.WriteLine($"检查手机号唯一性: {dto.PhoneNumber}");
                    var existingPhone = await _db.Users
                        .Where(u => !u.IsDeleted && u.Phone == dto.PhoneNumber && u.Id != userId)
                        .FirstOrDefaultAsync();

                    if (existingPhone != null)
                    {
                        Console.WriteLine($"手机号已存在: {dto.PhoneNumber}");
                        return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "手机号已存在");
                    }
                }
                else
                {
                    Console.WriteLine($"手机号未变化: {dto.PhoneNumber}");
                }
            }

            var changes = new List<string>();

            // 更新字段（允许与当前值相同，但会记录变化）
            if (!string.IsNullOrEmpty(dto.UserName))
            {
                var oldUsername = user.Username;
                user.Username = dto.UserName;
                changes.Add($"Username: {oldUsername} -> {dto.UserName}");
            }
            if (!string.IsNullOrEmpty(dto.Email))
            {
                var oldEmail = user.Email;
                user.Email = dto.Email;
                changes.Add($"Email: {oldEmail} -> {dto.Email}");
            }
            if (!string.IsNullOrEmpty(dto.PhoneNumber))
            {
                var oldPhone = user.Phone;
                user.Phone = dto.PhoneNumber;
                changes.Add($"Phone: {oldPhone} -> {dto.PhoneNumber}");
            }

            // 如果没有提供任何字段，返回错误
            if (string.IsNullOrEmpty(dto.UserName) && string.IsNullOrEmpty(dto.Email) && string.IsNullOrEmpty(dto.PhoneNumber))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "请至少提供一个要更新的字段");
            }

            // 更新修改时间
            user.UpdatedAt = DateTime.UtcNow;
            changes.Add($"UpdatedAt: {user.UpdatedAt}");
            Console.WriteLine($"准备保存更改: {string.Join(", ", changes)}");

            try
            {
                await _db.SaveChangesAsync();
                Console.WriteLine($"数据库保存成功");
            }
            catch (Microsoft.EntityFrameworkCore.DbUpdateException dbEx)
            {
                Console.WriteLine($"数据库更新异常: {dbEx.Message}");
                Console.WriteLine($"内部异常: {dbEx.InnerException?.Message}");
                
                // 检查是否是唯一性约束冲突
                if (dbEx.InnerException?.Message.Contains("duplicate key") == true || 
                    dbEx.InnerException?.Message.Contains("unique constraint") == true)
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "数据已存在，请检查用户名、邮箱或手机号是否已被使用");
                }
                
                // 检查是否是外键约束冲突
                if (dbEx.InnerException?.Message.Contains("foreign key") == true)
                {
                    return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "数据关联错误，请检查相关数据");
                }
                
                throw;
            }
            catch (Exception saveEx)
            {
                Console.WriteLine($"数据库保存失败: {saveEx.Message}");
                Console.WriteLine($"异常类型: {saveEx.GetType().Name}");
                Console.WriteLine($"内部异常: {saveEx.InnerException?.Message}");
                Console.WriteLine($"堆栈跟踪: {saveEx.StackTrace}");
                throw;
            }

            var result = new UserListDto
            {
                Id = user.Id,
                UserName = user.Username,
                Email = user.Email,
                PhoneNumber = user.Phone,
                Avatar = user.Avatar,
                AccountStatus = user.AccountStatus,
                LastLoginTime = user.LastLoginTime,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt,
                
            };

            return ApiResult.Success("更新用户成功", result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"更新用户时发生错误: {ex.Message}");
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部异常: {ex.InnerException.Message}");
            }
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"更新用户时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 删除用户（软删除）
    /// </summary>
    public async Task<ApiResult> DeleteUserAsync(Guid userId, Guid currentUserId)
    {
        try
        {
            // 不能删除自己
            if (userId == currentUserId)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "不能删除自己的账户");

            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");

            // 软删除用户
            user.IsDeleted = true;
            user.UpdatedAt = DateTime.UtcNow;

            await _db.SaveChangesAsync();

            return ApiResult.Success("删除用户成功");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"删除用户时发生错误: {ex.Message}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"删除用户时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    public async Task<ApiResult> ChangePasswordAsync(Guid userId, ChangePasswordDto dto, Guid currentUserId)
    {
        try
        {
            Console.WriteLine($"开始修改密码 - UserId: {userId}");
            
            // 验证新密码和确认密码
            if (dto.NewPassword != dto.ConfirmPassword)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "新密码和确认密码不匹配");

            // 验证新密码长度
            if (string.IsNullOrEmpty(dto.NewPassword) || dto.NewPassword.Length < 6)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "新密码长度不能少于6个字符");

            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");

            Console.WriteLine($"找到用户: {user.Username}");

            // 验证旧密码 - 使用与登录时相同的验证方式
            bool oldPasswordValid = false;
            
            try
            {
                // 使用与登录时相同的HashPassword方法验证
                var hashedOldPassword = HashPassword(dto.OldPassword, user.Salt);
                oldPasswordValid = (hashedOldPassword == user.Password);
                
                Console.WriteLine($"旧密码验证 - 输入密码: {dto.OldPassword}");
                Console.WriteLine($"旧密码验证 - 计算哈希: {hashedOldPassword}");
                Console.WriteLine($"旧密码验证 - 存储密码: {user.Password}");
                Console.WriteLine($"旧密码验证 - 结果: {oldPasswordValid}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"密码验证过程中发生异常: {ex.Message}");
                oldPasswordValid = false;
            }

            if (!oldPasswordValid)
            {
                Console.WriteLine("旧密码验证失败");
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "旧密码不正确");
            }
            
            Console.WriteLine("旧密码验证成功");

            // 生成新的密码哈希 - 使用与登录时相同的哈希方式
            var newHashedPassword = HashPassword(dto.NewPassword, user.Salt);
            Console.WriteLine($"新密码哈希生成成功");

            // 更新密码
            user.Password = newHashedPassword;
            user.UpdatedAt = DateTime.UtcNow;
            Console.WriteLine($"准备保存密码更新");

            await _db.SaveChangesAsync();
            Console.WriteLine($"密码更新保存成功");

            return ApiResult.Success("密码修改成功");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"修改密码时发生错误: {ex.Message}");
            Console.WriteLine($"异常类型: {ex.GetType().Name}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"内部异常: {ex.InnerException.Message}");
            }
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"修改密码时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 启用用户
    /// </summary>
    public async Task<ApiResult> EnableUserAsync(Guid userId, Guid currentUserId)
    {
        try
        {
            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");

            // 检查用户当前状态
            if (user.AccountStatus == 0)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户已经是启用状态");

            // 启用用户
            user.AccountStatus = 0; // 0: 正常状态
            user.UpdatedAt = DateTime.UtcNow;

            await _db.SaveChangesAsync();

            var result = new UserListDto
            {
                Id = user.Id,
                UserName = user.Username,
                Email = user.Email,
                PhoneNumber = user.Phone,
                Avatar = user.Avatar,
                AccountStatus = user.AccountStatus,
                LastLoginTime = user.LastLoginTime,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt
            };

            return ApiResult.Success("启用用户成功", result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"启用用户时发生错误: {ex.Message}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"启用用户时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 禁用用户
    /// </summary>
    public async Task<ApiResult> DisableUserAsync(Guid userId, Guid currentUserId)
    {
        try
        {
            // 不能禁用自己
            if (userId == currentUserId)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "不能禁用自己的账户");

            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");

            // 检查用户当前状态
            if (user.AccountStatus == 2)
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "用户已经是禁用状态");

            // 禁用用户
            user.AccountStatus = 2; // 2: 管理员手动禁用
            user.UpdatedAt = DateTime.UtcNow;

            await _db.SaveChangesAsync();

            var result = new UserListDto
            {
                Id = user.Id,
                UserName = user.Username,
                Email = user.Email,
                PhoneNumber = user.Phone,
                Avatar = user.Avatar,
                AccountStatus = user.AccountStatus,
                LastLoginTime = user.LastLoginTime,
                CreatedAt = user.CreatedAt,
                UpdatedAt = user.UpdatedAt
            };

            return ApiResult.Success("禁用用户成功", result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"禁用用户时发生错误: {ex.Message}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"禁用用户时发生错误: {ex.Message}");
        }
    }



    /// <summary>
    /// 哈希密码
    /// </summary>
    private string HashPassword(string password, string salt)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(password + salt);
        byte[] hash = SHA256.HashData(bytes);
        return Convert.ToBase64String(hash);
    }

    /// <summary>
    /// 验证密码
    /// </summary>
    private bool VerifyPassword(string password, string hashedPassword, string salt)
    {
        var computedHash = HashPassword(password, salt);
        return computedHash == hashedPassword;
    }

    /// <summary>
    /// 生成随机盐值
    /// </summary>
    private string GenerateRandomSalt()
    {
        byte[] saltBytes = new byte[16]; // 128 bits
        System.Security.Cryptography.RandomNumberGenerator.Fill(saltBytes);
        return Convert.ToBase64String(saltBytes);
    }    
} 